package org.jks.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Random;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.thoughtworks.xstream.core.util.Base64Encoder;

public class HttpUtil {
	public static final String REQUEST_TOKEN = "http://api.t.sina.com.cn/oauth/request_token";
	public static final String encoding = "UTF-8";
	public static final String OAUTH_CONSUMER_KEY = "oauth_consumer_key";
	public static final String CONSUMER_KEY_KEY = "consumer_key";
	public static final String OAUTH_NONCE_KEY = "oauth_nonce";
	public static final String OAUTH_SIGNATURE_METHOD_KEY = "oauth_signature_method";
	public static final String OAUTH_TIMESTAMP_KEY = "oauth_timestamp";
	public static final String OAUTH_SIGNATURE_KEY = "oauth_signature";
	public static final String OAUTH_VERSION_KEY = "oauth_version";
	public static final String OAUTH_CALLBACK_KEY = "oauth_callback";
	
	public static final String OAUTH_CALLBACK = "http://www.jkssss.pw";
	public static final String CONSUMER_KEY = "584400902";
	public static final String CONSUMER_SECRET = "32d8a5172796b2e08b0734a2b9f0ab96";
	public static final String ALGORITHM = "HmacSHA1";
	public static LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
	static {
		try {
			map.put(OAUTH_CALLBACK_KEY, URLEncoder.encode(OAUTH_CALLBACK, encoding));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		map.put(OAUTH_CONSUMER_KEY, CONSUMER_KEY);
		map.put(OAUTH_NONCE_KEY, oauthNonce());
		map.put(OAUTH_SIGNATURE_METHOD_KEY, "HMAC-SHA1");
		map.put(OAUTH_TIMESTAMP_KEY, timestamp());
		map.put(OAUTH_VERSION_KEY, "1.0");
	}

	public static String oauthNonce() {
		String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < 43; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	public static String timestamp() {
		Date date = new Date();
		long time = date.getTime();
		return (time + "").substring(0, 10);
	}

	public static String oauthSignature() throws Exception {
		String oauthKey = CONSUMER_SECRET + "&";
		Mac mac = Mac.getInstance(ALGORITHM);
        SecretKeySpec spec = new SecretKeySpec(oauthKey.getBytes(HTTP.ASCII),ALGORITHM);
        mac.init(spec);
        String bs = baseString("POST", REQUEST_TOKEN, map);
        byte[] byteHMAC = mac.doFinal((bs).getBytes(HTTP.ASCII));
        Base64Encoder base64 = new Base64Encoder();
        String oauthSignature = base64.encode(byteHMAC);
        System.out.println("oauthSignature:"+oauthSignature);
        return URLEncoder.encode(oauthSignature,encoding);
    }
	
	public static String baseString(String httpMethod, String url, LinkedHashMap<String, String> params) throws UnsupportedEncodingException{
		String bs = httpMethod + "&" + URLEncoder.encode(url,encoding) + "&";
		int i = 0;
		for(String key : params.keySet()){
			bs += URLEncoder.encode(key,encoding) + "%3D" + URLEncoder.encode(params.get(key),encoding);
			if((++i) != params.size()){
				bs += "%26";
			}
		}
		System.out.println("baseString:"+bs);
		return bs;
	}

	public static void main(String args[]) throws Exception {
		List <NameValuePair> params = new ArrayList<NameValuePair>(); 
        params.add(new BasicNameValuePair(OAUTH_NONCE_KEY, oauthNonce())); 
        params.add(new BasicNameValuePair(OAUTH_CALLBACK_KEY, URLEncoder.encode(OAUTH_CALLBACK, encoding)));
        params.add(new BasicNameValuePair(OAUTH_SIGNATURE_METHOD_KEY, "HMAC-SHA1"));
        params.add(new BasicNameValuePair(OAUTH_TIMESTAMP_KEY, timestamp()));
        params.add(new BasicNameValuePair(OAUTH_CONSUMER_KEY, URLEncoder.encode("584400902", encoding)));
        params.add(new BasicNameValuePair(OAUTH_SIGNATURE_KEY,oauthSignature()));
        params.add(new BasicNameValuePair(OAUTH_VERSION_KEY, "1.0"));
        HttpPost httpRequst = new HttpPost(REQUEST_TOKEN);
        httpRequst.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));  
		HttpResponse response = new DefaultHttpClient().execute(httpRequst);
		HttpEntity entity = response.getEntity();
		System.out.println("--------------------------------------");
		System.out.println(response.getStatusLine());
		if (entity != null) {
			String content = EntityUtils.toString(entity);
			System.out.println("Response content: " + URLDecoder.decode(content, encoding));
		}
	}
}
